package FenxiaoService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/tools/mylog"
)

// GetMemberGoodsDetailsBrokerage 在商品详情，获取显示的佣金
func GetMemberGoodsDetailsBrokerage(ctx context.Context, memberId, goodsId int) float64 {
	config, err := BaseGetConfig()
	if err != nil {
		mylog.ErrorLog("GetConfig " + err.Error())
		return 0
	}
	//  是否显示一级佣金
	if config.IsCommissionMoney == 0 {
		mylog.InfoLog("GetConfig 不开启佣金显示")
		// 不开启佣金显示
		return 0
	}

	flModel, err := GetMemberLevel(ctx, memberId)
	if err != nil {
		mylog.InfoLog("GetMemberLevel 获取返回")
		// 找不到分销商等级，返回 0
		return 0
	}
	// 获取到商品 等级 设置
	fglModel, err := GetGoodsLevel(ctx, goodsId, flModel.Id)
	if err != nil {
		mylog.ErrorLog("GetMemberGoodsDetailsBrokerage GetGoodsLevel " + err.Error())
		return 0
	}

	if fglModel == nil {
		// 有可能不存在数据的时候，说明没活动
		//mylog.ErrorLog("GetMemberGoodsDetailsBrokerage GetGoodsLevel 找不到数据")
		return 0
	}
	var rate float64
	if config.SelfPurchaseRebate == 1 {
		// 开启自购佣金
		rate = float64(fglModel.OneRate) / 100000.00
	} else {
		// 正常模式
		rate = float64(fglModel.TwoRate) / 100000.00
	}

	// 取出规格最高价钱
	maxPrice, err := toolsDb.GetUnSafaTable(ctx, "goods_option").As("go").LeftJoin("goods g", "go.goods_id = g.id").Where(
		"g.delete_at<1 AND go.delete_at<1 AND go.is_open = 1 AND go.goods_id = ?", goodsId).Max("go.sell_price")
	if err != nil {
		mylog.ErrorLog("GetMemberGoodsBrokerage goods_option " + err.Error())
		return 0
	}

	return rate * maxPrice
}
